﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using BbsbWebService.Classes.Plugins;
using BbsbWebService;

namespace BbsbWsGui
{
    internal class Prop
    {
        private PropertyInfo _prop;

        public Prop(PropertyInfo prop)
        {
            _prop = prop;
        }

        public string Name { get { return _prop.Name; } }
        public object Value { get; set; }
        public Type Type { get { return _prop.PropertyType; } }
        public string Description
        {
            get
            {
                string retVal = null;

                var bob = _prop.GetCustomAttributes(typeof(PluginAdditionalPropertyDescriptionAttribute), true);
                if (bob.Length > 0)
                {
                    var attrib = bob[0] as PluginAdditionalPropertyDescriptionAttribute;
                    retVal = attrib.Description;
                }
                return retVal;
            }
        }

        public PropertyInfo GetOriginal()
        {
            return _prop;
        }

        public bool TrySetValueAsType()
        {
            bool retVal = false;
            object original = Value;
            if (Value == null)
            {
                if ((Type.IsGenericType &&
                    Type.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) ||
                    Type == typeof(string))
                {
                    retVal = true;
                }
            }
            else if (Type == Value.GetType())
            {
                // it's already in the correct format...
                retVal = true;
            }
            else
            {
                try
                {
                    Value.ToString().ParseValueAsType(Value, Type);
                    retVal = true;
                }
                catch { }
            }

            return retVal;
        }
    }
}
